package com.example.royalchef.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.royalchef.R;
import com.example.royalchef.bean.LoginMessage;
import com.example.royalchef.utils.MD5Utils;
import com.example.royalchef.utils.PreferUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author: Administrator
 * created on: 2017/7/5 10:10
 * description:
 */

public class LoginActivity extends AppCompatActivity {
    @BindView(R.id.username)
    EditText etUserName;
    @BindView(R.id.login_password)
    EditText etPassword;
    //    @BindView(R.id.login)
//    Button btnLogin;
//    @BindView(R.id.bt_username_clear)
//    Button btnClearName;
//    @BindView(R.id.bt_pwd_clear)
//    Button btnClearPassword;
//    @BindView(R.id.register)
//    Button btnRegister;
    private String userName;
    private String password;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.login, R.id.bt_pwd_clear, R.id.bt_username_clear, R.id.register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:
                userName = etUserName.getText().toString().trim();
                password = etPassword.getText().toString().trim();
                if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
                    Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                RequestQueue queue = Volley.newRequestQueue(this);
                StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://192.168.12.248:8080/authentication/auth.json",
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                                try {
                                    JSONObject object = new JSONObject(response);
                                    JSONObject data = object.getJSONObject("data");
                                    String authToken = data.getString("authToken");
                                    PreferUtils.putString("authToken", authToken);
                                    getUserInfo(authToken);
                                    finish();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("username", userName);
                        map.put("password", MD5Utils.getStringMd5(password));
                        return map;
                    }
                };
                queue.add(stringRequest);
                break;
            case R.id.bt_username_clear:
                etUserName.setText("");
                break;
            case R.id.bt_pwd_clear:
                etPassword.setText("");
                break;
            case R.id.register:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void getUserInfo(final String authToken) {
        RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://192.168.12.248:8080/user/info.json",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            JSONObject data = object.getJSONObject("data");
                            LoginMessage loginMessage = new LoginMessage();
                            loginMessage.setImageUrl(data.getString("avatar"));
                            loginMessage.setName(data.getString("nickname"));
                            PreferUtils.putString("name", data.getString("nickname"));
                            PreferUtils.putString("avatar", data.getString("avatar"));
                            EventBus.getDefault().post(loginMessage);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("auth_token", authToken);
                return map;
            }
        };
        queue.add(stringRequest);

    }
}
